package com.netty.io.asyncio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author zhangbq
 * @since 2020-12-04 17:18
 **/
public class NioClient {
    public static void main(String[] args) throws IOException {
        //创建一个SocketChannel去跟服务端通信
        SocketChannel socketChannel = SocketChannel.open();
        //设置异步通信
        socketChannel.configureBlocking(true);
        InetSocketAddress socketAddress = new InetSocketAddress("localhost", 6666);
        //建立连接请求
        if (!socketChannel.connect(socketAddress)) {
            //没有成功连接一直重试
            while (!socketChannel.finishConnect()) {
                System.out.println("因为建立连接需要时间，客户端可以做其他业务");
            }
        }
        //成功建立连接之后，扔数据过去
        String request = "Hello, 这里是客户端，请求异步连接请求";
        ByteBuffer wrap = ByteBuffer.wrap(request.getBytes());
        //发送数据
        socketChannel.write(wrap);
        System.in.read();
    }
}
